//图片处理
export function getImg(data) {
	return data.thum.map(({
		extname,
		name,
		url
	}) => {
		return {
			extname,
			name,
			url,
		};
	});
}
//价格初始化
export function priceFrom(money) {
	return (money / 100).toFixed(2)
}
//折扣标签
export function discount(money, deMoney) {
	let count = parseInt((money / deMoney) * 100);
	if (count == 0) {
		return '骨折';
	} else if (count > 100) {
		return '涨价了';
	} else {
		return count + '折';
	}
}
//页面权限
//获取用户身份
export function getUserRole(goPage = false) {
	let userInfo = uniCloud.getCurrentUserInfo();
	if (!userInfo.uid || userInfo.role.includes('merchant')) {
		if (goPage) {
			uni.showToast({
				icon: 'none',
				title: '访问权限不足'
			});
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/shop/index'
				});
			}, 1000);
		}
	}
	return true;
}

//获取昵称
export function giveName(item) {
	return item.nickname || item.username || item.mobile || "请设置昵称"
}

//获取默认头像
export function giveAvatar(item) {
	return item?.avatar_file?.url ?? '/static/images/panda.jpg'
}


//时间戳格式化
export function timeFormat(time, fmt = 'yyyy-MM-dd hh:mm:ss', targetTimezone = 8) {
	try {
		if (!time) {
			return "";
		}
		if (typeof time === "string" && !isNaN(time)) time = Number(time);
		// 其他更多是格式化有如下:
		// yyyy-MM-dd hh:mm:ss|yyyy年MM月dd日 hh时MM分等,可自定义组合
		let date;
		if (typeof time === "number") {
			if (time.toString().length == 10) time *= 1000;
			date = new Date(time);
		} else {
			date = time;
		}

		const dif = date.getTimezoneOffset();
		const timeDif = dif * 60 * 1000 + (targetTimezone * 60 * 60 * 1000);
		const east8time = date.getTime() + timeDif;

		date = new Date(east8time);
		let opt = {
			"M+": date.getMonth() + 1, //月份
			"d+": date.getDate(), //日
			"h+": date.getHours(), //小时
			"m+": date.getMinutes(), //分
			"s+": date.getSeconds(), //秒
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度
			"S": date.getMilliseconds() //毫秒
		};
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for (let k in opt) {
			if (new RegExp("(" + k + ")").test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (opt[k]) : (("00" + opt[k]).substr(("" + opt[k])
					.length)));
			}
		}
		return fmt;
	} catch (err) {
		// 若格式错误,则原值显示
		return time;
	}
};